package com.quanyan.club.service.impl;

import com.github.ltsopensource.core.json.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.movement.*;
import com.quanyan.club.entity.vo.resp.movement.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.ActivityCRUDService;
import com.quanyan.club.service.ClubMovementService;
import com.quanyan.club.web.ClubActivityController;
import com.quanyan.comment.reqeust.ReqCommentParam;
import com.quanyan.comment.reqeust.ReqCommentQuery;
import com.quanyan.comment.response.RespComment;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.Limit;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.user.request.ReqNewsTopic;
import com.quanyan.user.request.ReqUserFollow;
import com.quanyan.user.response.*;
import com.quanyan.user.serviceFacade.UserDynamicServiceFacade;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author xian-guo
 * @email 498152332@qq.com
 * @date 2016/11/30.
 */
@Service("clubMovementService")
public class ClubMovementServiceImpl implements ClubMovementService {

    private static Logger logger = Logger.getLogger(ClubActivityController.class);

    @Value("${club_movement_share_url}")
    private String shareUrl;//分享动态链接

    @Autowired
    private TbClubMovementMapper tbClubMovementMapper;//动态详情

    @Autowired
    private UserServiceFacade userServiceFacade;//用户模块

    @Autowired
    private UserDynamicServiceFacade userDynamicServiceFacade;//话题

    @Autowired
    private TbClubMovementImagesMapper tbClubMovementImagesMapper;//动态图片视频

    @Autowired
    private TbActivityMapper tbActivityMapper;//活动信息

    @Autowired
    private TbActivityPosterMapper tbActivityPosterMapper;//活动海报

    @Autowired
    private PlaceClient placeClient;//场馆信息

    @Autowired
    private TbActivityMultimediaMapper tbActivityMultimediaMapper;//活动相册

    @Autowired
    private ClubMovementMapper clubMovementMapper;//sql俱乐部活动信息

    @Autowired
    private TbClubMovementPraiseMapper tbClubMovementPraiseMapper;//动态点赞

    @Autowired
    private CommentServiceFacade commentServiceFacade;//用户中心评论模块

    @Autowired
    private TbClubMemberMapper tbClubMemberMapper;//用户成员

    @Autowired
    private TbClubMapper tbClubMapper;

    /**
     * 获取俱乐部动态
     * ReqClubListInfo map中参数：clubId
     * @param reqClubListInfo
     * @return
     */
    @Override
    public APIResponse<PageObj<List<RespMovementListInfo>>> getMovementListInfo(ReqClubListInfo reqClubListInfo) {
        Map<String,Object> paramMap=reqClubListInfo.getParamMap();
        if (!paramMap.containsKey("clubId")){
            return APIResponse.returnFail("俱乐部编号不能为空");
        }
        Integer clubId= (Integer) paramMap.get("clubId");
        Integer uId=null;
        if (paramMap.containsKey("uId")){
            uId= (Integer) paramMap.get("uId");
        }
        TbClubMovementExample tbClubMovementExample=new TbClubMovementExample();
        tbClubMovementExample.createCriteria().andClubidEqualTo(clubId).andIsDeleteEqualTo((byte) 0);
        tbClubMovementExample.setOrderByClause(" create_time DESC");
        //俱乐部下面总动态数
        int totalCount=tbClubMovementMapper.countByExample(tbClubMovementExample);
        tbClubMovementExample.setLimit(Limit.buildLimit(reqClubListInfo.getPageNum()+1,reqClubListInfo.getPageSize()));
        List<TbClubMovement> tbClubMovementList=tbClubMovementMapper.selectByExample(tbClubMovementExample);
        //构建返回对象
        List<RespMovementListInfo> respMovementListInfoList=new ArrayList<>();
        if (CollectionUtils.isEmpty(tbClubMovementList)){//无查询结果，构建空对象返回
            return APIResponse.returnSuccess(PageObj.create(totalCount,reqClubListInfo.getPageNum(),reqClubListInfo.getPageSize(),respMovementListInfoList));
        }
        List<Integer> followList=new ArrayList<>();//发布动态用户id，查询当前用户是否关注
        for (TbClubMovement tbClubMovement:tbClubMovementList){
            RespMovementListInfo respMovementListInfo=new RespMovementListInfo();
            respMovementListInfo.setMvId(tbClubMovement.getId());//动态id
            respMovementListInfo.setCreateTime(tbClubMovement.getCreateTime());//时间
            respMovementListInfo.setCurPosition(tbClubMovement.getPosition());//位置
            respMovementListInfo.setContent(tbClubMovement.getContent());//内容
            respMovementListInfo.setuId(tbClubMovement.getUid());//发布动态的用户id
            followList.add(tbClubMovement.getUid());
            //点赞数
            TbClubMovementPraiseExample tbClubMovementPraiseExample=new TbClubMovementPraiseExample();
            TbClubMovementPraiseExample.Criteria criteria=tbClubMovementPraiseExample.createCriteria();
            criteria.andMvmentIdEqualTo(tbClubMovement.getId());
            int priceCount=tbClubMovementPraiseMapper.countByExample(tbClubMovementPraiseExample);
            respMovementListInfo.setSumPraises(priceCount);
            respMovementListInfo.setFollowed(false);//是否关注
            //该动态当前用是否点赞
            respMovementListInfo.setPraise(false);
            if (null!=uId){
                criteria.andUidEqualTo(uId);
                List<TbClubMovementPraise> tbClubMovementPraises=tbClubMovementPraiseMapper.selectByExample(tbClubMovementPraiseExample);
                if (!CollectionUtils.isEmpty(tbClubMovementPraises)){
                    respMovementListInfo.setPraise(true);
                }
            }
            respMovementListInfo.setSumComments(tbClubMovement.getSumComments());//评论数
            respMovementListInfo.setType(tbClubMovement.getType());//手动发布0r被动
            respMovementListInfo.setShareUrl(shareUrl+tbClubMovement.getId()+"&clubId="+clubId);//分享链接
            //查询用户头像昵称等信息
            APIResponse<RespUserInfoBase> apiResponse=userServiceFacade.queryUserInfo(tbClubMovement.getUid());
            logger.warn("---调用户中心头像-------------->>>"+JSON.toJSONString(apiResponse));
            if (apiResponse.isRet()){
                RespUserInfoBase respUserInfoBase=apiResponse.getData();
                respMovementListInfo.setUserImageUrl(respUserInfoBase.getIcon());//头像
                respMovementListInfo.setNickName(respUserInfoBase.getNickName());//昵称
            }
            //查询动态图片或视频
            if (tbClubMovement.getPicOrVideo()==0){//获取图片
                TbClubMovementImagesExample tbClubMovementImagesExample=new TbClubMovementImagesExample();
                tbClubMovementImagesExample.createCriteria().andMvmentIdEqualTo(tbClubMovement.getId()).andIsDeleteEqualTo((byte) 0);
                tbClubMovementImagesExample.setOrderByClause(" pic_order ASC");//顺序排序
                List<TbClubMovementImages> tbClubMovementImagesList=tbClubMovementImagesMapper.selectByExample(tbClubMovementImagesExample);
                List<PictureObj> urlList=new ArrayList<>();//构建动态图片list-url返回对象
                if(!CollectionUtils.isEmpty(tbClubMovementImagesList)){
                    for (TbClubMovementImages tbClubMovementImages:tbClubMovementImagesList){
                        PictureObj pictureObj=new PictureObj();
                        pictureObj.setPicWidth(tbClubMovementImages.getPicWidth());
                        pictureObj.setPicHeight(tbClubMovementImages.getPicHeigth());
                        pictureObj.setPicUrl(tbClubMovementImages.getNormalUrl());
                        urlList.add(pictureObj);
                    }
                }
                respMovementListInfo.setPicUrlList(urlList);//设置动态图片对象
            }else {//获取视频，以后版本

            }
            //关联话题，查询用户中心话题
            Integer topicId=tbClubMovement.getTopicId();
            if (topicId>0){//标示选了热表话题标签
                ReqNewsTopic reqNewsTopic=new ReqNewsTopic();
                reqNewsTopic.setTopicId(topicId);
                PageObj<List<RespNewsTopic>> pageObj=userDynamicServiceFacade.findAllTopic(reqNewsTopic);//用户中心获取热门话题
                logger.warn("---调用户中心热门话题-------------->>>"+JSON.toJSONString(pageObj));
                List<RespNewsTopic> respNewsTopicList=pageObj.getItems();
                if (!CollectionUtils.isEmpty(respNewsTopicList)){
                    RespNewsTopic respNewsTopic=respNewsTopicList.get(0);
                    respMovementListInfo.setTopicContent(respNewsTopic.getName());//设置话题
                }
            }
            //关联活动，查询活动信息
            ClubActivityInfo clubActivityInfo=null;
            Integer activityId=tbClubMovement.getActivityId();
            if (activityId!=0){//标示关联了活动，查询活动信息
                TbActivity tbActivity=tbActivityMapper.selectByPrimaryKey(activityId);
                if (null !=tbActivity){
                    clubActivityInfo=new ClubActivityInfo();
                    Integer posterId=tbActivity.getPosterPicId();//查询海报图片url
                    TbActivityPoster tbActivityPoster=tbActivityPosterMapper.selectByPrimaryKey(posterId);
                    clubActivityInfo.setImageUrl(tbActivityPoster.getUrl());//活动海报
                    clubActivityInfo.setActivityName(tbActivity.getName());//活动名称
                    clubActivityInfo.setStartTime(tbActivity.getStartTime());//活动开始时间
                    clubActivityInfo.setEndTime(tbActivity.getEndTime());//活动结束
                    clubActivityInfo.setActivityId(tbActivity.getId());//活动id
                    clubActivityInfo.setCategoryId(tbActivity.getCategoryId());//俱乐部分类
                    Integer palceId=tbActivity.getPlaceId();
                    if (palceId>0){//去场馆查询地址
                        Map<Integer,PlaceDubboProvider> placeMap=placeClient.getPlaceBySinglePlaceId(palceId);
                        logger.warn("---调场馆查询活动地址-------------->>>"+JSON.toJSONString(placeMap));
                        if (null!=placeMap){
                            PlaceDubboProvider provider=placeMap.get(palceId);
                            clubActivityInfo.setAddress(provider.getAddress());//设置活动地址
                        }
                    }else{//查询place_address字段
                        clubActivityInfo.setAddress(tbActivity.getPlaceAddress());
                    }
                }
                respMovementListInfo.setClubActivityInfo(clubActivityInfo);
            }
            respMovementListInfoList.add(respMovementListInfo);
        }
        //查询动态是否关注
        if (null !=uId){
            APIResponse<List<Integer>> apiResponseFollow=userDynamicServiceFacade.batchIsUserFollow(uId,followList);
            logger.warn("-------批量查询是否关注--------"+JSON.toJSONString(apiResponseFollow));
            if(apiResponseFollow.isRet()){
                List<Integer> uIdList=apiResponseFollow.getData();
                for (int i=0;i<uIdList.size();i++){
                    RespMovementListInfo respMovementListInfo=respMovementListInfoList.get(i);
                    if(respMovementListInfo.getuId().equals(uIdList.get(i))){
                        respMovementListInfo.setFollowed(true);
                    }
                }
            }
        }
        return APIResponse.returnSuccess(PageObj.create(totalCount,reqClubListInfo.getPageNum(),reqClubListInfo.getPageSize(),respMovementListInfoList));
    }

    /**
     * 发布动态
     * @param reqSubmitMovement
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public APIResponse submitMovementInfo(ReqSubmitMovement reqSubmitMovement) {
            ReqReleaseDynamic reqReleaseDynamic=new ReqReleaseDynamic();
        reqReleaseDynamic.setUid(reqSubmitMovement.getuId());
        reqReleaseDynamic.setActivityId(reqSubmitMovement.getActivityId());
        reqReleaseDynamic.setClubId(reqSubmitMovement.getClubId());
        reqReleaseDynamic.setContent(reqSubmitMovement.getContent());
        byte type=reqSubmitMovement.getType();
        reqReleaseDynamic.setReleaseType((int) type);
        reqReleaseDynamic.setType(2);
        reqReleaseDynamic.setTopicId(reqSubmitMovement.getTopicId());
        List<PictureObj> pictureObjs= reqSubmitMovement.getPicObjList();
        if (type==0){//发布类型0--主动，1--被动
            reqReleaseDynamic.setReportAddress(reqSubmitMovement.getPosition());
            reqReleaseDynamic.setLat(reqSubmitMovement.getLat());
            reqReleaseDynamic.setLng(reqSubmitMovement.getLng());
            if (com.quanyan.club.pullclub.utils.CollectionUtils.isEmpty(pictureObjs)){
                return APIResponse.returnFail("系统错误，图片不能为空!");
            }
            List<ReqImage> reqImages=new ArrayList<>();
            for (PictureObj pictureObj:pictureObjs){
                ReqImage reqImage=new ReqImage();
                reqImage.setUrl(pictureObj.getPicUrl());
                reqImage.setHeight(pictureObj.getPicHeight());
                reqImage.setWidth(pictureObj.getPicWidth());
                reqImages.add(reqImage);
            }
            reqReleaseDynamic.setImageObjs(reqImages);

        }else if (type==1){
            List<ReqImage> reqImages=new ArrayList<>();
            TbActivityMultimediaExample tbActivityMultimediaExample=new TbActivityMultimediaExample();
            tbActivityMultimediaExample.createCriteria().andActivityIdEqualTo(reqSubmitMovement.getActivityId());
            List<TbActivityMultimedia> tbActivityMultimediaList=tbActivityMultimediaMapper.selectByExample(tbActivityMultimediaExample);
            if (CollectionUtils.isEmpty(tbActivityMultimediaList)) {//没有相册，取海报图片
                TbActivity tbActivity=tbActivityMapper.selectByPrimaryKey(reqSubmitMovement.getActivityId());
                TbActivityPoster tbActivityPoster=tbActivityPosterMapper.selectByPrimaryKey(tbActivity.getPosterPicId());
                ReqImage reqImage = new ReqImage();
                reqImage.setUrl(tbActivityPoster.getUrl());
                reqImages.add(reqImage);
            }else {
                byte i = 0;
                for (TbActivityMultimedia tbActivityMultimedia : tbActivityMultimediaList) {
                    if (i >= 9) {//最多取活动相册中的九张图片发布到动态中
                        break;
                    }
                    i++;
                    ReqImage reqImage = new ReqImage();
                    reqImage.setUrl(tbActivityMultimedia.getMultimediaUrl());
                    reqImages.add(reqImage);
                }
            }
            reqReleaseDynamic.setImageObjs(reqImages);
        }
        APIResponse apiResponse=userDynamicServiceFacade.addDynamicDetail(reqReleaseDynamic);
        if (apiResponse.isRet() && apiResponse.getErrcode()==200){
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("发布动态失败，请重试!");
//        TbClubMemberExample tbClubMemberExample=new TbClubMemberExample();
//        tbClubMemberExample.createCriteria().andClubIdEqualTo(reqSubmitMovement.getClubId()).andUidEqualTo(reqSubmitMovement.getuId()).andIsDeleteEqualTo((byte) 0);
//        List<TbClubMember> tbClubMemberList=tbClubMemberMapper.selectByExample(tbClubMemberExample);
//        if (CollectionUtils.isEmpty(tbClubMemberList)){//非俱乐部成员无法发动态
//            return APIResponse.returnFail("您还不是该俱乐部成员");
//        }
//        TbClubMovement tbClubMovement=new TbClubMovement();
//        tbClubMovement.setUid(reqSubmitMovement.getuId());
//        tbClubMovement.setActivityId(reqSubmitMovement.getActivityId());//活动id
//        tbClubMovement.setClubid(reqSubmitMovement.getClubId());//俱乐部id
//        tbClubMovement.setPicOrVideo(reqSubmitMovement.getPicOrVideo());//图片or视频标志
//        tbClubMovement.setTopicId(reqSubmitMovement.getTopicId());//话题 没选0
//        tbClubMovement.setContent(reqSubmitMovement.getContent());//发布内容  自动发布为俱乐部名称
//        tbClubMovement.setCreateTime(new Date());
//        byte type=reqSubmitMovement.getType();
//        tbClubMovement.setType(type);//发布类型0--主动，1--被动
//        if(reqSubmitMovement.getPicOrVideo()==0 && type==0){//主动发布才存位置，被动发布不传位置
//            tbClubMovement.setPosition(reqSubmitMovement.getPosition());//位置,
//            tbClubMovement.setLng(reqSubmitMovement.getLng());//经度
//            tbClubMovement.setLat(reqSubmitMovement.getLat());//纬度
//        } else if (reqSubmitMovement.getPicOrVideo()==0 && type==1){//被动发布，去取俱乐部名称
//            tbClubMovement.setContent(tbClubMapper.selectByPrimaryKey(reqSubmitMovement.getClubId()).getClubName());//发布内容  自动发布为俱乐部名称
//        }
//        int upCount=tbClubMovementMapper.insertSelective(tbClubMovement);//发布动态
//        if (upCount>0){
//            if (reqSubmitMovement.getPicOrVideo()==0 && type==0){//发布的是图片  主动发布
//                List<PictureObj> imageUrlList=reqSubmitMovement.getPicObjList();//获取图片对象
//                if(!CollectionUtils.isEmpty(imageUrlList)){
//                    byte i=0;
//                    for (PictureObj obj:imageUrlList){
//                        i++;
//                        TbClubMovementImages tbClubMovementImages=new TbClubMovementImages();
//                        tbClubMovementImages.setMvmentId(tbClubMovement.getId());//动态详情id
//                        tbClubMovementImages.setNormalUrl(obj.getPicUrl());//设置每张图片url
//                        tbClubMovementImages.setPicOrder(i);//设置图片顺序
//                        tbClubMovementImages.setPicWidth(obj.getPicWidth());//图片宽度
//                        tbClubMovementImages.setPicHeigth(obj.getPicHeight());//图片高度
//                        tbClubMovementImages.setCreateTime(new Date());//创建时间
//                        int count=tbClubMovementImagesMapper.insertSelective(tbClubMovementImages);
//                        if (count==0){//没有插入成功
//                            throw  new BizException("发布动态图片失败");
//                        }
//                    }
//                }
//                return APIResponse.returnSuccess();
//            }else if(reqSubmitMovement.getPicOrVideo()==0 && type==1){//被动发布图片从活动相册中取
//                TbActivityMultimediaExample tbActivityMultimediaExample=new TbActivityMultimediaExample();
//                tbActivityMultimediaExample.createCriteria().andActivityIdEqualTo(reqSubmitMovement.getActivityId());
//                List<TbActivityMultimedia> tbActivityMultimediaList=tbActivityMultimediaMapper.selectByExample(tbActivityMultimediaExample);
//                if (!CollectionUtils.isEmpty(tbActivityMultimediaList)){
//                    byte i=0;
//                    for (TbActivityMultimedia tbActivityMultimedia:tbActivityMultimediaList){
//                        if(i>=9){//最多取活动相册中的九张图片发布到动态中
//                            break;
//                        }
//                        i++;
//                        TbClubMovementImages tbClubMovementImages=new TbClubMovementImages();
//                        tbClubMovementImages.setMvmentId(tbClubMovement.getId());//动态详情id
//                        tbClubMovementImages.setNormalUrl(tbActivityMultimedia.getMultimediaUrl());//设置每张图片url
//                        tbClubMovementImages.setPicOrder(i);//设置图片顺序
//                        tbClubMovementImages.setCreateTime(new Date());//创建时间
//                        int count=tbClubMovementImagesMapper.insertSelective(tbClubMovementImages);
//                        if (count==0){//没有插入成功
//                            throw  new BizException("发布动态失败");
//                        }
//                    }
//                }
//                return APIResponse.returnSuccess();
//            }else{//发布的是视频，后续版本
//                return APIResponse.returnSuccess();
//            }
//        }
//        return APIResponse.returnFail("发布动态失败");
    }

    /**
     * reqClubListInfo map中参数：clubId
     * 查询俱乐部关联活动
     * @param reqClubListInfo
     * @return
     */
    @Override
    public APIResponse<PageObj<List<RespClubActivityInfo>>> getClubBindActivity(ReqClubListInfo reqClubListInfo) {
        Map<String,Object> paramMap=reqClubListInfo.getParamMap();
        Integer clubId= (Integer) paramMap.get("clubId");
        if (null==clubId){
            return APIResponse.returnFail("俱乐部编号不能为空");
        }
        paramMap.put("pageNum",reqClubListInfo.getPageNum()*reqClubListInfo.getPageSize());
        paramMap.put("pageSize",reqClubListInfo.getPageSize());
        List<ClubActivityInfo> clubActivityInfoList= clubMovementMapper.queryClubActivityListByClubId(paramMap);//查询俱乐部活动
        List<RespClubActivityInfo> respClubActivityInfoList=new ArrayList<>();//返回集合
        int totalCount=0;//俱乐部活动数量
        if (!CollectionUtils.isEmpty(clubActivityInfoList)){
            totalCount= clubMovementMapper.queryClubActivityListByClubIdCount(clubId);
            for (ClubActivityInfo clubActivityInfo:clubActivityInfoList){
                int placeId=clubActivityInfo.getPlaceId();
                if (placeId>0){//去场馆查询地址
                    Map<Integer,PlaceDubboProvider> placeMap=placeClient.getPlaceBySinglePlaceId(placeId);
                    logger.warn("---调场馆查地址-------------->>>"+JSON.toJSONString(paramMap));
                    if (null!=placeMap){
                        PlaceDubboProvider provider=placeMap.get(placeId);
                        clubActivityInfo.setAddress(provider.getAddress());//设置活动地址
                        logger.warn("place address-------------->>>>>>"+provider.getAddress());
                    }
                }
                RespClubActivityInfo respClubActivityInfo=new RespClubActivityInfo();//构建返回对象
                respClubActivityInfo.setAddress(clubActivityInfo.getAddress());//地址
                respClubActivityInfo.setActivityName(clubActivityInfo.getActivityName());//俱乐部名称
                respClubActivityInfo.setImageUrl(clubActivityInfo.getImageUrl());//海报
                respClubActivityInfo.setStartTime(clubActivityInfo.getStartTime());//开始时间
                respClubActivityInfo.setEndTime(clubActivityInfo.getEndTime());//结束时间
                respClubActivityInfo.setActivityId(clubActivityInfo.getActivityId());//活动id;
                respClubActivityInfoList.add(respClubActivityInfo);
            }
        }
        return APIResponse.returnSuccess(PageObj.create(totalCount,reqClubListInfo.getPageNum(),reqClubListInfo.getPageSize(),respClubActivityInfoList));
    }

    /**
     * 给动态点赞
     * @param reqPointPrise
     * @return
     */
    @Override
    public APIResponse setPointPrise(ReqPointPrise reqPointPrise) {
        byte type=reqPointPrise.getType();//点赞 or 取消点赞
        TbClubMovementPraiseExample tbClubMovementPraiseExample=new TbClubMovementPraiseExample();
        tbClubMovementPraiseExample.createCriteria().andMvmentIdEqualTo(reqPointPrise.getMvId()).andUidEqualTo(reqPointPrise.getuId());//某个动态点赞记录
        List<TbClubMovementPraise> tbClubMovementPraiseList=tbClubMovementPraiseMapper.selectByExample(tbClubMovementPraiseExample);
        if (type==1){//点赞
            if (CollectionUtils.isEmpty(tbClubMovementPraiseList)){//没有点赞过某个动态,可以点赞
                TbClubMovementPraise tbClubMovementPraise=new TbClubMovementPraise();
                tbClubMovementPraise.setUid(reqPointPrise.getuId());//用户id
                tbClubMovementPraise.setMvmentId(reqPointPrise.getMvId());//动态id
                tbClubMovementPraise.setCreateTime(new Date());//点赞时间
                tbClubMovementPraise.setType(type);//1--赞 2--取消赞
                int isertCount=tbClubMovementPraiseMapper.insertSelective(tbClubMovementPraise);
                if (isertCount>0){//点赞成功
                    return APIResponse.returnSuccess();
                }
            }
        }else if (type==2){//取消点赞
            if (!CollectionUtils.isEmpty(tbClubMovementPraiseList)){//点赞过某个动态，才可以取消点赞
                TbClubMovementPraise tbClubMovementPraise=tbClubMovementPraiseList.get(0);
                int isertCount=tbClubMovementPraiseMapper.deleteByPrimaryKey(tbClubMovementPraise.getId());//删除记录
                if (isertCount>0){//取消点赞成功
                    return APIResponse.returnSuccess();
                }
            }
        }
        return APIResponse.returnFail("赞失败");
    }

    /**
     * 发表评论
     * @param reqSendCommentMovement
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public APIResponse sendCommentToMovement(ReqSendCommentMovement reqSendCommentMovement) {
        int count= clubMovementMapper.updateMovementSumComment(reqSendCommentMovement.getMovementId());//根据评论id添加评论数量
        if (count>0){
            ReqCommentParam reqCommentParam=new ReqCommentParam();
            reqCommentParam.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            reqCommentParam.setBusinessCode(Constants.CLUB_MOVEMENT_BUSINESS_CODE);
            reqCommentParam.setCommentType(reqSendCommentMovement.getCommentType());//评论类型 1：评论 2：回复
            reqCommentParam.setBusinessId(reqSendCommentMovement.getMovementId());//动态id
            reqCommentParam.setFromUserId(reqSendCommentMovement.getFromUserId());//评论人
            reqCommentParam.setCommentContent(reqSendCommentMovement.getCommentContent());//评论内容
            if (reqSendCommentMovement.getCommentType()==2){//如果是回复某人，设置@用户id,否则为空
                reqCommentParam.setToUserId(reqSendCommentMovement.getToUserId());//@用户
                reqCommentParam.setReplayId(reqSendCommentMovement.getReplayId());//评论动态的评论id
            }
            APIResponse commentSucd= commentServiceFacade.commentAdd(reqCommentParam);
            logger.warn("-----发表评论--------->>>>"+ JSON.toJSONString(commentSucd));
            if (!commentSucd.isRet()){
                throw new BizException("发表评论失败");
            }
            return APIResponse.returnSuccess("发表评论成功");
        }
        return APIResponse.returnFail("发表评论失败");
    }

    /**
     * 动态详情
     * @param mvId
     * @return
     */
    @Override
    public APIResponse<RespClubMovementDetail> getMovementDetail(Integer mvId,Integer uId) {
        if (null == mvId){
            return APIResponse.returnFail("动态id不能为空");
        }
        TbClubMovement tbClubMovement=tbClubMovementMapper.selectByPrimaryKey(mvId);
        if (0!=tbClubMovement.getIsDelete()){
            return APIResponse.returnFail("该动态已被删除或隐藏");
        }
        //构建返回对象
        RespClubMovementDetail respClubMovementDetail=new RespClubMovementDetail();
        respClubMovementDetail.setMvId(tbClubMovement.getId());//动态id
        respClubMovementDetail.setCreateTime(tbClubMovement.getCreateTime());//时间
        respClubMovementDetail.setCurPosition(tbClubMovement.getPosition());//位置
        respClubMovementDetail.setContent(tbClubMovement.getContent());//内容
        respClubMovementDetail.setuId(tbClubMovement.getUid());//发布动态的用户id
        respClubMovementDetail.setType(tbClubMovement.getType());//0--手动发布，1--自动发布
        //点赞数
        TbClubMovementPraiseExample tbClubMovementPraiseExample=new TbClubMovementPraiseExample();
        TbClubMovementPraiseExample.Criteria criteria=tbClubMovementPraiseExample.createCriteria();
        criteria.andMvmentIdEqualTo(tbClubMovement.getId());
        tbClubMovementPraiseExample.setOrderByClause(" create_time desc");
        int priceCount=tbClubMovementPraiseMapper.countByExample(tbClubMovementPraiseExample);
        respClubMovementDetail.setSumPraises(priceCount);
        //是否关注
        respClubMovementDetail.setFollowed(false);
        if(uId>0){
            APIResponse<List<Integer>> apiResponseFollow=userDynamicServiceFacade.batchIsUserFollow(uId, Arrays.asList(tbClubMovement.getUid()));
            logger.warn("-------动态详情用户中心是否关注------->>>>>>>>>>>>"+JSON.toJSONString(apiResponseFollow));
            if (apiResponseFollow.isRet()){
                List<Integer> follow=apiResponseFollow.getData();
                if (!CollectionUtils.isEmpty(follow)){
                    respClubMovementDetail.setFollowed(true);
                }
            }
        }
        //点赞人头像集合
        tbClubMovementPraiseExample.setLimit(Limit.buildLimit(0,7));
        List<TbClubMovementPraise> tbClubMovementPraiseList=tbClubMovementPraiseMapper.selectByExample(tbClubMovementPraiseExample);
        List<Integer> iconList=new ArrayList<>();
        for (TbClubMovementPraise tbClubPraise:tbClubMovementPraiseList){
            iconList.add(tbClubPraise.getUid());
        }
        //当前用户是否点赞
        respClubMovementDetail.setPraise(false);
        if (uId>0){
            criteria.andUidEqualTo(uId);
            List<TbClubMovementPraise> tbClubMovementPraises=tbClubMovementPraiseMapper.selectByExample(tbClubMovementPraiseExample);
            if (!CollectionUtils.isEmpty(tbClubMovementPraises)){
                respClubMovementDetail.setPraise(true);
            }
        }
        APIResponse<List<RespUserInfoBase>> apiResponseUser=userServiceFacade.batchQueryUserInfo(iconList);//根据uid批量获取用户信息
        logger.warn("---动态详情调用户中心个人信息-------------->>>"+JSON.toJSONString(apiResponseUser));
        if (apiResponseUser.isRet()) {
            List<String> userUrlPraise=new ArrayList<>();
            List<RespUserInfoBase> respUserInfoBaseList=apiResponseUser.getData();
            for (Integer id:iconList){//根据点赞时间排序，用户中心查询结果可能不匹配顺序
                for (RespUserInfoBase userInfoBase:respUserInfoBaseList){
                    if (id.equals(userInfoBase.getUid())){
                        userUrlPraise.add(userInfoBase.getIcon());
                        break;
                    }
                }
            }
            respClubMovementDetail.setUserUrlList(userUrlPraise);//设置头像集合返回
        }
        respClubMovementDetail.setSumComments(tbClubMovement.getSumComments());//评论数
        respClubMovementDetail.setShareUrl(shareUrl+tbClubMovement.getId()+"&clubId="+tbClubMovement.getClubid());//分享链接
        //查询用户头像昵称等信息
        APIResponse<RespUserInfoBase> apiResponse=userServiceFacade.queryUserInfo(tbClubMovement.getUid());
        logger.warn("---调用户中心头像-------------->>>"+JSON.toJSONString(apiResponse));
        if (apiResponse.isRet()){
            RespUserInfoBase respUserInfoBase=apiResponse.getData();
            respClubMovementDetail.setUserImageUrl(respUserInfoBase.getIcon());//头像
            respClubMovementDetail.setNickName(respUserInfoBase.getNickName());//昵称
        }
        //查询动态图片或视频
        if (tbClubMovement.getPicOrVideo()==0){//获取图片
            TbClubMovementImagesExample tbClubMovementImagesExample=new TbClubMovementImagesExample();
            tbClubMovementImagesExample.createCriteria().andMvmentIdEqualTo(tbClubMovement.getId()).andIsDeleteEqualTo((byte) 0);
            tbClubMovementImagesExample.setOrderByClause(" pic_order ASC");//顺序排序
            List<TbClubMovementImages> tbClubMovementImagesList=tbClubMovementImagesMapper.selectByExample(tbClubMovementImagesExample);
            List<PictureObj> picList=new ArrayList<>();//构建list-url返回对象
            if(!CollectionUtils.isEmpty(tbClubMovementImagesList)){
                for (TbClubMovementImages tbClubMovementImages:tbClubMovementImagesList){
                    PictureObj pictureObj=new PictureObj();
                    pictureObj.setPicWidth(tbClubMovementImages.getPicWidth());
                    pictureObj.setPicHeight(tbClubMovementImages.getPicHeigth());
                    pictureObj.setPicUrl(tbClubMovementImages.getNormalUrl());
                    picList.add(pictureObj);
                }
            }
            respClubMovementDetail.setPicUrlList(picList);//设置动态图片url
        }else {//获取视频，以后版本

        }
        //关联话题，查询用户中心话题
        Integer topicId=tbClubMovement.getTopicId();
        if (topicId>0){//标示选了热表话题标签
            ReqNewsTopic reqNewsTopic=new ReqNewsTopic();
            reqNewsTopic.setTopicId(topicId);
            PageObj<List<RespNewsTopic>> pageObj=userDynamicServiceFacade.findAllTopic(reqNewsTopic);//用户中心获取热门话题
            logger.warn("---调用户中心话题-------------->>>"+JSON.toJSONString(pageObj));
            List<RespNewsTopic> respNewsTopicList=pageObj.getItems();
            if (!CollectionUtils.isEmpty(respNewsTopicList)){
                RespNewsTopic respNewsTopic=respNewsTopicList.get(0);
                respClubMovementDetail.setTopicContent(respNewsTopic.getName());//设置话题
            }
        }
        //关联活动，查询活动信息
        ClubActivityInfo clubActivityInfo=null;
        Integer activityId=tbClubMovement.getActivityId();
        if (activityId!=0){//标示关联了活动，查询活动信息
            TbActivity tbActivity=tbActivityMapper.selectByPrimaryKey(activityId);
            if (null !=tbActivity){
                clubActivityInfo=new ClubActivityInfo();
                Integer posterId=tbActivity.getPosterPicId();//查询海报图片url
                TbActivityPoster tbActivityPoster=tbActivityPosterMapper.selectByPrimaryKey(posterId);
                clubActivityInfo.setImageUrl(tbActivityPoster.getUrl());//活动海报
                clubActivityInfo.setActivityName(tbActivity.getName());//活动名称
                clubActivityInfo.setStartTime(tbActivity.getStartTime());//活动开始时间
                clubActivityInfo.setEndTime(tbActivity.getEndTime());//活动结束
                clubActivityInfo.setActivityId(tbActivity.getId());//活动id
                clubActivityInfo.setCategoryId(tbActivity.getCategoryId());//俱乐部分类
                Integer palceId=tbActivity.getPlaceId();
                if (palceId>0){//去场馆查询地址
                    Map<Integer,PlaceDubboProvider> placeMap=placeClient.getPlaceBySinglePlaceId(palceId);
                    logger.warn("---调场馆查活动地址-------------->>>"+JSON.toJSONString(placeMap));
                    if (null!=placeMap){
                        PlaceDubboProvider provider=placeMap.get(palceId);
                        clubActivityInfo.setAddress(provider.getAddress());//设置活动地址
                    }
                }else{//查询place_address字段
                    clubActivityInfo.setAddress(tbActivity.getPlaceAddress());
                }
            }
            respClubMovementDetail.setClubActivityInfo(clubActivityInfo);
        }
        return APIResponse.returnSuccess(respClubMovementDetail);
    }

    /**
     * 获取动态评论
     * @param reqClubListInfo
     * @return
     */
    @Override
    public APIResponse<PageObj<List<MovementComment>>> getMovementComment(ReqClubListInfo reqClubListInfo) {
        Map<String,Object> paramMap=reqClubListInfo.getParamMap();
        Integer mvId= (Integer) paramMap.get("mvId");
        if (null == mvId){
            return APIResponse.returnFail("动态id不能为空");
        }
        TbClubMovement tbClubMovement=tbClubMovementMapper.selectByPrimaryKey(mvId);
        if (0!=tbClubMovement.getIsDelete()){
            return APIResponse.returnFail("该动态已被删除或隐藏");
        }
        //查询评论
        ReqCommentQuery reqCommentQuery=new ReqCommentQuery();
        reqCommentQuery.setSystemCode(Constants.CLUB_SYSTEM_CODE);
        reqCommentQuery.setBusinessCode(Constants.CLUB_MOVEMENT_BUSINESS_CODE);
        reqCommentQuery.setBusinessId(tbClubMovement.getId());//动态id
        reqCommentQuery.setPageNum(reqClubListInfo.getPageNum());
        reqCommentQuery.setPageSize(reqClubListInfo.getPageSize());
        APIResponse<PageObj<List<RespComment>>> apiResponseComment=commentServiceFacade.commentQuery(reqCommentQuery);
        logger.warn("--用户中心评论返回结果---->>>>"+JSON.toJSONString(apiResponseComment));
        if (apiResponseComment.isRet()){
            List<MovementComment> movementComments=new ArrayList<>();//返回评论集合
            PageObj<List<RespComment>> result=apiResponseComment.getData();
            List<RespComment> respCommentList=result.getItems();
            if (!CollectionUtils.isEmpty(respCommentList)){
                List<Integer> nickNameList=new ArrayList<>();//评论人昵称集合
                List<Integer> userNameList=new ArrayList<>();//@人昵称集合
                for (RespComment respComment:respCommentList){
                    MovementComment movementComment=new MovementComment();
                    movementComment.setBusinessId(respComment.getBusinessId());//动态id
                    movementComment.setCommentContent(respComment.getCommentContent());//评论内容
                    movementComment.setFromUser(respComment.getFromUser());//评论人
                    movementComment.setCreateTime(respComment.getCreateTime());//创建时间
                    movementComment.setId(respComment.getId());//评论id
                    movementComment.setCommentType(respComment.getCommentType());//1评论，2,回复
                    nickNameList.add(respComment.getFromUser());
                    if (2==respComment.getCommentType()){//回复
                        movementComment.setToUser(respComment.getToUser());//@人
                        userNameList.add(respComment.getToUser());
                        movementComment.setReplayId(respComment.getReplayId());//为回复时，评论id
                    }
                    movementComments.add(movementComment);
                }
                //批量根据用户id查询用户信息
                APIResponse<List<RespUserInfoDetail>> apiResponseNickName=userServiceFacade.batchQueryUserInfoDetail(nickNameList);//查询评论人信息
                logger.warn("-评论信息返回结果1----"+JSON.toJSONString(apiResponseNickName));
                if(apiResponseNickName.isRet()){
                    List<RespUserInfoDetail> userInfoNick=apiResponseNickName.getData();
                    for (MovementComment moveComment:movementComments){
                        for (RespUserInfoDetail userInfo:userInfoNick){
                            if (moveComment.getFromUser().equals(userInfo.getUid())){//评论
                                moveComment.setNickName(userInfo.getNickName());//评论人名称
                                moveComment.setUserIcon(userInfo.getIcon());//评论人头像
                                if (userInfo.getIsBidsVerifyDe()==0 && userInfo.getIsBuyoutVerifyDe()==0){//不是达人
                                    moveComment.setMaster(0);
                                }else {
                                    moveComment.setMaster(1);//是达人
                                }
                                break;
                            }
                        }
                    }
                }
                APIResponse<List<RespUserInfoDetail>> apiResponseUserName=userServiceFacade.batchQueryUserInfoDetail(userNameList);//查询@人信息
                logger.warn("-回复评论信息返回结果2----"+JSON.toJSONString(apiResponseUserName));
                if(apiResponseUserName.isRet()){
                    List<RespUserInfoDetail> userInfoUser=apiResponseUserName.getData();
                    if (!CollectionUtils.isEmpty(userInfoUser)){
                        for (MovementComment moveComment:movementComments){
                            for (RespUserInfoDetail userInfo:userInfoUser){
                                    if(2==moveComment.getCommentType() && moveComment.getToUser().equals(userInfo.getUid())){//查@用户的昵称
                                        moveComment.setUserName(userInfo.getNickName());//@人名称
                                        if (userInfo.getIsBidsVerifyDe()==0 && userInfo.getIsBuyoutVerifyDe()==0){//不是达人
                                            moveComment.setMaster(0);
                                        }else {
                                            moveComment.setMaster(1);//是达人
                                        }
                                        break;
                                    }
                                }
                            }
                    }
                }
            }
            return APIResponse.returnSuccess(PageObj.create(result.getTotal(),result.getPageNum(),result.getSize(),movementComments));
        }
        return APIResponse.returnFail("查询评论失败");
    }

    /**
     * 点赞用户列表展示页面
     * 参数  当前登录用户id：userId; 动态id:mvId
     * @param reqClubListInfo
     * @return
     */
    @Override
    public APIResponse<PageObj<List<PraiseListUserInfo>>> getMovementPraiseList(ReqClubListInfo reqClubListInfo) {
        Map<String,Object> paramMap=reqClubListInfo.getParamMap();
        Integer mvId= (Integer) paramMap.get("mvId");
        if (null == mvId){
            return APIResponse.returnFail("动态id不能为空");
        }
        TbClubMovementPraiseExample tbClubMovementPraiseExample=new TbClubMovementPraiseExample();
        tbClubMovementPraiseExample.createCriteria().andMvmentIdEqualTo(mvId);
        tbClubMovementPraiseExample.setOrderByClause(" create_time DESC");
        int praiseCount=tbClubMovementPraiseMapper.countByExample(tbClubMovementPraiseExample);//点赞总数
        tbClubMovementPraiseExample.setLimit(Limit.buildLimit(reqClubListInfo.getPageNum()+1,reqClubListInfo.getPageSize()));
        List<TbClubMovementPraise> tbClubMovementPraiseList=tbClubMovementPraiseMapper.selectByExample(tbClubMovementPraiseExample);//查询动态所有赞的用户id
        if (CollectionUtils.isEmpty(tbClubMovementPraiseList)){//如果没有人点赞,非法请求
            return APIResponse.returnSuccess(ApiResponseEnum.ILLEGAL_PROTOCOL);
        }
        List<Integer> uIdList=new ArrayList<>();
        for (TbClubMovementPraise praise:tbClubMovementPraiseList){
            uIdList.add(praise.getUid());
        }
        ReqUserFollow reqUserFollow=new ReqUserFollow();
        reqUserFollow.setUid((Integer) paramMap.get("uId"));
        reqUserFollow.setLstFriendUid(uIdList);
        APIResponse<List<RespUserFollow>> listAPIResponse=userDynamicServiceFacade.queryUserFriendService(reqUserFollow);//查询赞用户信息及是否关注
        logger.warn("--------调用户模块查询是否关注------------>>>>>>>>>>>>"+JSON.toJSONString(listAPIResponse));
        if (listAPIResponse.isRet()){
            List<RespUserFollow> respUserFollowList=listAPIResponse.getData();
            if (!CollectionUtils.isEmpty(respUserFollowList)){
                List<PraiseListUserInfo> praiseListUserInfoList=new ArrayList<>();
                for (RespUserFollow respUserFollow:respUserFollowList){
                    RespUserInfoBase respUserInfoBase=respUserFollow.getRespUserInfoBase();//用户信息对象
                    PraiseListUserInfo praiseListUserInfo=new PraiseListUserInfo();//返回对象
                    praiseListUserInfo.setuId(respUserInfoBase.getUid());//用户id
                    praiseListUserInfo.setUserIcon(respUserInfoBase.getIcon());//头像
                    praiseListUserInfo.setNickName(respUserInfoBase.getNickName());//昵称
                    praiseListUserInfo.setGender(respUserInfoBase.getGender());//性别
                    praiseListUserInfo.setIsFollow(respUserFollow.getIsFollow());//0：否，1：是
                    praiseListUserInfo.setIsFriend(respUserFollow.getIsFriend());//0：否，1：是
                    praiseListUserInfoList.add(praiseListUserInfo);
                }
                return APIResponse.returnSuccess(PageObj.create(praiseCount,reqClubListInfo.getPageNum(),reqClubListInfo.getPageSize(),praiseListUserInfoList));
            }
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("查询列表失败");
    }

    /**
     * 删除动态或评论
     * @param paramMap
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public APIResponse delMovementCommentAndMovement(Map<String,Object> paramMap) {
        Integer uId= (Integer) paramMap.get("uId");//用户id
        Integer type= (Integer) paramMap.get("type");//1:动态 2：评论
        Integer paramId= (Integer) paramMap.get("paramId");//删除id
        Integer clubId= (Integer) paramMap.get("clubId");//俱乐部id
        if (1==type){//删除动态
            TbClubMemberExample tbClubMemberExample=new TbClubMemberExample();
            tbClubMemberExample.createCriteria().andUidEqualTo(uId).andClubIdEqualTo(clubId).andIsDeleteEqualTo((byte) 0);
            List<TbClubMember> clubMemberList=tbClubMemberMapper.selectByExample(tbClubMemberExample);
            if (CollectionUtils.isEmpty(clubMemberList)){//判断当前用户的角色，是否有删除权限
                return APIResponse.returnFail(ApiResponseEnum.ILLEGAL_PROTOCOL);
            }
            TbClubMember tbClubMember=clubMemberList.get(0);
            Integer priority=tbClubMember.getPriority();
            if (priority==1 || priority==2 || priority==3){//主席可以删除任何人
                return this.delMovement(paramId);
            }
            if (priority==4){//普通成员
                TbClubMovementExample tbClubMovementExample=new TbClubMovementExample();
                tbClubMemberExample.createCriteria().andUidEqualTo(uId).andIsDeleteEqualTo((byte) 0).andIdEqualTo(paramId).andClubIdEqualTo(clubId);
                int countNum=tbClubMovementMapper.countByExample(tbClubMovementExample);
                if (countNum>0){
                    return this.delMovement(paramId);
                }
            }
        }else if (2==type){//删除评论
            Integer mvId= (Integer) paramMap.get("mvId");//删除评论，传动态id
            int commCount=clubMovementMapper.updateMovementCommentCount(mvId);//更新评论数
            if (commCount>0){
                APIResponse apiResponse=commentServiceFacade.commentDel(paramId);
                if (apiResponse.isRet()){
                    return APIResponse.returnSuccess("删除评论成功");
                }
            }
        }
        return APIResponse.returnFail("删除失败");
    }

    private APIResponse<String> delMovement(int paramId){
        TbClubMovementPraiseExample tbClubMovementPraiseExample=new TbClubMovementPraiseExample();
        tbClubMovementPraiseExample.createCriteria().andMvmentIdEqualTo(paramId);
        int delPraiSucc=tbClubMovementPraiseMapper.deleteByExample(tbClubMovementPraiseExample);//删除点赞
        int delMov= clubMovementMapper.updateMovementDelete(paramId);//删除动态
        int delImag= clubMovementMapper.updateMovementImageDelete(paramId);//删除动态对应的图片
        if(delMov>0){
            logger.warn("------调用户中心删除动态下所有评论---------");
            ReqCommentQuery reqCommentQuery=new ReqCommentQuery();
            reqCommentQuery.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            reqCommentQuery.setBusinessCode(Constants.CLUB_MOVEMENT_BUSINESS_CODE);
            reqCommentQuery.setBusinessId(paramId);//动态id
            APIResponse apiResponse=commentServiceFacade.delDynamicComment(reqCommentQuery);
            if (!apiResponse.isRet()){
                throw new BizException("删除异常");
            }
            return APIResponse.returnSuccess("删除成功");
        }
        return APIResponse.returnFail("删除失败");
    }

}
